"use client";
import classNames from "classnames";
import { memo } from "react";
import type { FC, MutableRefObject } from "react";
import { produce } from "immer";
import { DragDropContext, Draggable, Droppable } from "@hello-pangea/dnd";
import contentStyle from "../../index.module.scss";
import MainItem from "../../components/mainItem";
import Panel from "../../components/mainItem/panel";
import AddItemBtn from "../components/addItemBtn";
import styles from "./index.module.scss";
import { useContentStore, useServerStore, useStore } from "@/store";
import Eyes from "@/app/components/Eyes";
import { reorder } from "@/app/utils";
import { getTimeRange, skillsOptions } from "@/cvcomponents/common/utils";

function getItemStyle(isDragging: boolean, draggableStyle: any) {
  return {
    background: isDragging ? "rgb(233, 242, 253)" : "",
    ...draggableStyle,
  };
}

function getListStyle(isDraggingOver: boolean) {
  return {
    width: "100%",
  };
}
const { Head } = MainItem;
interface IndexProps {
  type: Sections;
  scrollWrapper: MutableRefObject<any>;
}

const Index: FC<IndexProps> = memo(
  ({ type, scrollWrapper }) => {
    // resetServerContext()
    const { content, updateSection } = useContentStore(
      (state) => state,
      (o, n) => {
        return o.content[type] === n.content[type];
      }
    );
    const serverStore = useServerStore();

    const { setCurrentTab, setIndex } = useStore();

    const data = content[type];

    const renderInfo = (item: Entries) => {
      const t = [item.title, item.subTitle].filter(Boolean);

      return (
        <div className={styles.info}>
          {t.length ? <div>{t.join(",")}</div> : null}
          <div className={styles.itemTime}>
            {getTimeRange(item.startDate, item.endDate)}
          </div>
          {item.description ? (
            <div
              className={styles.description}
              unselectable="off"
              dangerouslySetInnerHTML={{ __html: item.description }}
            ></div>
          ) : null}
          {item.list && item.list.length ? (
            <div
              className={styles.selectedItemWraper}
              style={{ marginTop: item.description ? "10px" : "0px" }}
            >
              {item.list.map((l) => {
                return (
                  <span key={l.name} className={styles.selectedItem}>
                    {l.name}
                    {l.value
                      ? `：${
                          skillsOptions?.find((t) => t.value === l.value)?.label
                        }`
                      : ""}
                  </span>
                );
              })}
            </div>
          ) : null}
        </div>
      );
    };
    const onEdit = (i) => {
      setCurrentTab(`${type}Edit`);
      setIndex(i);
    };
    const getList = (id: string) => {
      if (id === type) return data.entries;
    };
    const onDragEnd = async (result: any) => {
      if (scrollWrapper.current) {
        scrollWrapper.current.style.overflowY = "scroll";
      }
      const { source, destination, el } = result;
      el.current.style.height = "auto";
      if (!destination) return;

      if (source.droppableId === destination.droppableId) {
        if (result.destination.index === result.source.index) {
          return;
        }
        const list = reorder(
          getList(source.droppableId),
          source.index,
          destination.index
        );
        if (
          list?.map((item) => `${item.id}${item.key}`).join() !==
          data?.entries.map((item) => `${item.id}${item.key}`).join()
        ) {
          updateSection(
            produce(data, (draft) => {
              if (draft) {
                draft.entries = list;
              }
            }),
            type
          );
          if (data.id) {
            await serverStore.sortEntry(
              data.id,
              list.map((l) => l.id)
            );
          }
        }
      }
    };
    return (
      <div className={classNames(styles.contentItem, contentStyle.card)}>
        <MainItem>
          <Head type={type}></Head>
          <Panel
            hasNoAddBtn={
              data.sectionType === "skills" ||
              data.sectionType === "custom" ||
              data.sectionType === "selfevaluation" ||
              data.sectionType === "certificate"
            }
          >
            {(el) => {
              return (
                <>
                  <DragDropContext
                    onDragEnd={(e) => onDragEnd({ ...e, el })}
                    onBeforeDragStart={(e) => {
                      if (scrollWrapper.current) {
                        scrollWrapper.current.style.overflowY = "hidden";
                      }
                      el.current.style.height = "100%";
                    }}
                    onDragStart={(e) => {}}
                  >
                    <Droppable droppableId={type}>
                      {(provided, snapshot) => {
                        return (
                          <div
                            {...provided.droppableProps}
                            ref={provided.innerRef}
                            style={getListStyle(snapshot.isDraggingOver)}
                          >
                            {data?.entries.map((item, index) => {
                              return (
                                <Draggable
                                  shouldRespectForcePress
                                  key={item.id ? item.id : item.key}
                                  draggableId={`${
                                    item.id ? item.id : item.key
                                  }`}
                                  index={index}
                                >
                                  {(provided, snapshot) => {
                                    return (
                                      <div
                                        ref={provided.innerRef}
                                        {...provided.draggableProps}
                                        style={getItemStyle(
                                          snapshot.isDragging,
                                          provided.draggableProps.style
                                        )}
                                      >
                                        <div className={styles.item}>
                                          <div
                                            className={styles.itemTitleWraper}
                                          >
                                            <div
                                              className={styles.dragHandle}
                                              {...provided.dragHandleProps}
                                              onClick={() => {
                                                onEdit(index);
                                              }}
                                            >
                                              <div
                                                className={classNames(
                                                  styles.itemTitle,
                                                  {
                                                    [styles.itemTitleDisabled]:
                                                      item.isHidden,
                                                  }
                                                )}
                                              >
                                                <svg
                                                  style={{
                                                    width: "20px",
                                                    marginRight: "4px",
                                                  }}
                                                  xmlns="http://www.w3.org/2000/svg"
                                                  viewBox="0 0 30 30"
                                                  fill="currentColor"
                                                >
                                                  <path
                                                    fill="none"
                                                    stroke="currentColor"
                                                    strokeLinecap="round"
                                                    strokeLinejoin="round"
                                                    strokeMiterlimit="10"
                                                    strokeWidth="2"
                                                    d="M25 15L5 15M25 10L5 10M25 20L5 20"
                                                  ></path>
                                                  <path d="M11 6L19 6 15 2zM19 24L11 24 15 28z"></path>
                                                </svg>
                                                {renderInfo(item)}
                                              </div>
                                              <div
                                                className={styles.cover}
                                              ></div>
                                            </div>
                                            <Eyes
                                              isHidden={item.isHidden}
                                              onChange={async (e) => {
                                                if (item.id) {
                                                  const res =
                                                    await serverStore.toggleHideEntry(
                                                      {
                                                        id: item.id,
                                                        isHidden: e,
                                                      }
                                                    );
                                                  if (res) {
                                                    updateSection(
                                                      produce(data, (draft) => {
                                                        if (draft) {
                                                          draft.entries[
                                                            index
                                                          ].isHidden = e;
                                                        }
                                                      }),
                                                      type
                                                    );
                                                  }
                                                } else {
                                                  updateSection(
                                                    produce(data, (draft) => {
                                                      if (draft) {
                                                        draft.entries[
                                                          index
                                                        ].isHidden = e;
                                                      }
                                                    }),
                                                    type
                                                  );
                                                }
                                              }}
                                            ></Eyes>
                                          </div>
                                        </div>
                                      </div>
                                    );
                                  }}
                                </Draggable>
                              );
                            })}
                            {provided.placeholder}
                          </div>
                        );
                      }}
                    </Droppable>
                  </DragDropContext>
                  {data.sectionType !== "skills" &&
                  data.sectionType !== "custom" &&
                  data.sectionType !== "selfevaluation" &&
                  data.sectionType !== "certificate" ? (
                    <AddItemBtn
                      onEdit={() => {
                        onEdit?.(data?.entries.length || 0);
                      }}
                    ></AddItemBtn>
                  ) : null}
                </>
              );
            }}
          </Panel>
        </MainItem>
      </div>
    );
  },
  () => {
    return true;
  }
);
Index.displayName = "contentItem";
export default Index;
